<template>
  <div class="form-item-el">
    <div v-if="mode === 'DESIGN'">
      <el-button disabled type="primary" size="small" round> 选择部门</el-button>
      <span class="placeholder"> {{ placeholder }}</span>
    </div>
    <div v-else-if="mode === 'PC' && !readonly" style="max-width: 350px">
      <el-button type="primary" size="small" round @click="$refs.orgPicker.show()"> 选择部门</el-button>
      <org-picker type="dept" :multiple="multiple" ref="orgPicker" :selected="_value" @ok="selected" />
      <span class="placeholder"> {{ placeholder }}</span>
      <div style="margin-top: 5px">
        <el-tag size="small" style="margin: 5px" closable v-for="(dept, i) in _value" :key="dept.id" @close="delDept(i)">{{
          dept.name
        }}</el-tag>
      </div>
    </div>
    <div v-else>
      {{ String(_value.map(v => v.name)) }}
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import OrgPicker from "../OrgPicker/index.vue";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  mode: {
    type: String,
    default: "DESIGN"
  },
  required: {
    type: Boolean,
    default: false
  },
  readonly: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: "请选择部门"
  },
  multiple: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["update:modelValue"]);

const showOrgSelect = ref(false);
const _value = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const deptDesc = computed({
  get() {
    if (_value.value && _value.value.length > 3) {
      return `${String(_value.value.slice(0, 3).map(v => v.name))}... 等${_value.value.length}个部门`;
    } else if (_value.value && _value.value.length > 0) {
      return String(_value.value.map(v => v.name));
    } else {
      return null;
    }
  },
  set() {}
});

const selected = values => {
  showOrgSelect.value = false;
  _value.value = values;
};
const delDept = i => {
  _value.value.splice(i, 1);
};
</script>

<style scoped>
.placeholder {
  margin-left: 10px;
  color: #adabab;
  font-size: smaller;
}
</style>
